package com.scqzy.shengchunqiang.sword2offer.day18;

import com.scqzy.shengchunqiang.structure.TreeNode;

import java.util.Objects;

/**
 * @Description: 剑指 Offer 55 - II. 平衡二叉树
 * @Author 盛春强
 * @Date 2021/8/25 19:40
 */
public class IsBalanced {
    public boolean isBalanced(TreeNode root) {
        if (Objects.isNull(root)) {
            return true;
        }
        return isBalanced(root.left) && isBalanced(root.right) && (Math.abs(depth(root.left) - depth(root.right)) < 2);
    }

    private int depth(TreeNode root) {
        if (Objects.isNull(root)) {
            return 0;
        }
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }
}
